<?php

namespace Home\DAO;

use Home\Service\IdGenService;
use Home\Service\UserService;
use Home\Service\PinyinService;

/**
 * 运单 DAO
 *
 * @author 李静波
 */
class ExpressDAO extends PSIBaseDAO {
	private $LOG_CATEGORY = "运单管理";

	/**
	 * 寄件
	 */
	public function addExpressBill($params) {
		$ref = $params["ref"];
		$startPlace = $params["startPlace"];
		$destPlace = $params["destPlace"];
		$startPlaceId = $params["startPlaceId"];
		$destPlaceId = $params["destPlaceId"];
		$recName = $params["recName"];
		$recAddress = $params["recAddress"];
		$recTel = $params["recTel"];
		$customerId = $params["customerId"];
		$sendAddress = $params["sendAddress"];
		$sendTel = $params["sendTel"];
		$cargo = $params["cargo"];
		$fragile = $params["fragile"];
		$freight = $params["freight"];
		$payment = $params["payment"];
		$claimValue = $params["claimValue"];
		$cargoMoney = $params["cargoMoney"];
		$memo = $params["memo"];
		
		$db = M();
		$db->startTrans();
		
		// 检查单号是否被使用过了
		if ($ref) {
			$sql = "select count(*) as cnt from t_express_bill where ref = '%s' ";
			$data = $db->query($sql, $ref);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("单号[$ref]已经被使用，请重新选择单号");
			}
		}
		
		// 检查客户是否存在
		$sql = "select name from t_customer where id = '%s' ";
		$data = $db->query($sql, $customerId);
		if (! $data) {
			$db->rollback();
			return $this->bad("选择的客户不存在");
		}
		$sendName = $data[0]["name"];
		
		$idGen = new IdGenService();
		$id = $idGen->newId($db);
		
		$us = new UserService();
		$companyId = $us->getCompanyId();
		$dataOrg = $us->getLoginUserDataOrg();
		
		$sql = "insert into t_express_bill (id, ref, rec_name, rec_address, rec_tel, send_name,
					send_address, send_tel, cargo, is_fragile, bill_dt, freight, payment,
					claim_value, cargo_money, status, memo, data_org, company_id, customer_id,
					start_place, dest_place, send_district_id, rec_district_id) 
				values ('%s', '%s', '%s', '%s', '%s', '%s',
					'%s', '%s', '%s', %d, now(), %f, %d,
					%f, %f, 200, '%s', '%s', '%s', '%s',
					'%s', '%s', '%s', '%s')";
		$rc = $db->execute($sql, $id, $ref, $recName, $recAddress, $recTel, $sendName, $sendAddress, 
				$sendTel, $cargo, $fragile, $freight, $payment, $claimValue, $cargoMoney, $memo, 
				$dataOrg, $companyId, $customerId, $startPlace, $destPlace, $startPlaceId, 
				$destPlaceId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 运单跟踪信息
		$userId = $us->getLoginUserId();
		
		$sql = "insert into t_express_tracing (ref, bill_id, status_before, status_after, 
				changed_dt, op_user_id, memo)
				values ('%s', '%s', 0, 200, now(), '%s', '寄件')";
		$rc = $db->execute($sql, $ref, $id, $userId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$bd = new BizlogDAO($db);
		$log = "寄件，新建运单单号[$ref]";
		$bd->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok();
	}

	/**
	 * 单据状态标志转化为显示文字
	 */
	private function billStatusCodeToLable($status) {
		switch ($status) {
			case 100 :
				return "待收件";
			case 200 :
				return "已收件";
			case 300 :
				return "货物达到仓库";
			case 400 :
				return "派送中";
			case 500 :
				return "已签收";
			default :
				return "";
		}
	}

	/**
	 * 付款方式编码转化为显示文字
	 */
	private function paymentCodeToLabel($payment) {
		switch ($payment) {
			case 10 :
				return "现金";
			case 20 :
				return "到付";
			case 30 :
				return "月结";
			default :
				return "";
		}
	}

	/**
	 * 运单列表
	 */
	public function expressList($params) {
		$start = $params["start"];
		$limit = $params["limit"];
		
		$billStatus = $params["billStatus"];
		$ref = $params["ref"];
		
		$db = M();
		$queryParams = array();
		$sql = "select e.id, e.status, e.ref, e.rec_name, e.rec_address, e.rec_tel, e.send_name,
					e.send_address, e.send_tel, e.cargo, e.is_fragile, e.bill_dt, e.freight, 
					e.payment, e.claim_value, e.cargo_money, e.memo, e.start_place, e.dest_place,
					e.send_courier_user_id
				from t_express_bill e
				where 1 = 1 ";
		
		if ($billStatus != - 1) {
			$sql .= " and e.status = %d ";
			$queryParams[] = $billStatus;
		}
		
		if ($ref) {
			$sql .= " and e.ref like '%s' ";
			$queryParams[] = "%$ref%";
		}
		
		$sql .= " order by e.ref desc
				  limit %d , %d";
		$queryParams[] = $start;
		$queryParams[] = $limit;
		
		$data = $db->query($sql, $queryParams);
		$result = array();
		foreach ( $data as $i => $v ) {
			$result[$i]["id"] = $v["id"];
			$result[$i]["ref"] = $v["ref"];
			$result[$i]["recName"] = $v["rec_name"];
			$result[$i]["recAddress"] = $v["rec_address"];
			$result[$i]["recTel"] = $v["rec_tel"];
			$result[$i]["sendName"] = $v["send_name"];
			$result[$i]["sendAddress"] = $v["send_address"];
			$result[$i]["sendTel"] = $v["send_tel"];
			$result[$i]["cargo"] = $v["cargo"];
			$result[$i]["isFragile"] = $v["is_fragile"] == 1 ? "易碎" : "";
			$result[$i]["billDT"] = $this->toYMD($v["bill_dt"]);
			$result[$i]["freight"] = $v["freight"];
			$result[$i]["payment"] = $this->paymentCodeToLabel($v["payment"]);
			$result[$i]["claimValue"] = $v["claim_value"];
			$result[$i]["cargoMoney"] = $v["cargo_money"];
			$result[$i]["memo"] = $v["memo"];
			$result[$i]["startPlace"] = $v["start_place"];
			$result[$i]["destPlace"] = $v["dest_place"];
			$result[$i]["status"] = $this->billStatusCodeToLable($v["status"]);
			
			$expressManId = $v["send_courier_user_id"];
			if ($expressManId) {
				$sql = "select name
						from t_express_man
						where id = '%s' ";
				$d = $db->query($sql, $expressManId);
				if ($d) {
					$result[$i]["expressMan"] = $d[0]["name"];
				}
			}
		}
		
		$queryParams = array();
		$sql = "select count(*) as cnt
				from t_express_bill
				where 1 = 1 ";
		
		if ($billStatus != - 1) {
			$sql .= " and status = %d ";
			$queryParams[] = $billStatus;
		}
		
		if ($ref) {
			$sql .= " and ref like '%s' ";
			$queryParams[] = "%$ref%";
		}
		$data = $db->query($sql, $queryParams);
		$cnt = $data[0]["cnt"];
		
		return array(
				"dataList" => $result,
				"totalCount" => $cnt
		);
	}

	/**
	 * 运单变更详情
	 */
	public function expressTracing($params) {
		$id = $params["id"];
		
		$db = M();
		
		$sql = "select t.ref, t.status_before, t.status_after, t.changed_dt, t.memo,
					u.name as user_name
				from t_express_tracing t, t_user u
				where t.bill_id = '%s' and t.op_user_id = u.id
				order by t.changed_dt";
		
		$data = $db->query($sql, $id);
		$result = array();
		
		foreach ( $data as $i => $v ) {
			$result[$i]["ref"] = $v["ref"];
			$result[$i]["statusBefore"] = $this->billStatusCodeToLable($v["status_before"]);
			$result[$i]["statusAfter"] = $this->billStatusCodeToLable($v["status_after"]);
			$result[$i]["changedDT"] = $v["changed_dt"];
			$result[$i]["memo"] = $v["memo"];
			$result[$i]["userName"] = $v["user_name"];
		}
		
		return $result;
	}

	/**
	 * 获得某个运单的详情
	 */
	public function expressBillInfo($params) {
		$id = $params["id"];
		
		$db = M();
		
		$sql = "select ref, rec_name, rec_address, rec_tel, send_name, send_address, send_tel,
					cargo, is_fragile, freight, payment, claim_value, cargo_money, memo, customer_id,
					status, start_place, dest_place, rec_district_id, send_district_id
				from t_express_bill
				where id = '%s' ";
		$data = $db->query($sql, $id);
		$v = $data[0];
		$result = array();
		
		$result["ref"] = $v["ref"];
		$result["recName"] = $v["rec_name"];
		$result["recAddress"] = $v["rec_address"];
		$result["recTel"] = $v["rec_tel"];
		$result["customerName"] = $v["send_name"];
		$result["customerId"] = $v["customer_id"];
		$result["sendAddress"] = $v["send_address"];
		$result["sendTel"] = $v["send_tel"];
		$result["cargo"] = $v["cargo"];
		$result["isFragile"] = $v["is_fragile"];
		$result["freight"] = $v["freight"];
		$result["payment"] = $v["payment"];
		$result["claimValue"] = $v["claim_value"];
		$result["cargoMoney"] = $v["cargo_money"];
		$result["memo"] = $v["memo"];
		$result["status"] = $v["status"];
		$result["startPlace"] = $v["start_place"];
		$result["destPlace"] = $v["dest_place"];
		$result["startPlaceId"] = $v["send_district_id"];
		$result["destPlaceId"] = $v["rec_district_id"];
		
		return $result;
	}

	/**
	 * 运单变更
	 */
	public function editExpressBill($params) {
		$id = $params["id"];
		$status = $params["status"];
		
		$ref = $params["ref"];
		$startPlace = $params["startPlace"];
		$destPlace = $params["destPlace"];
		
		$startPlaceId = $params["startPlaceId"];
		$destPlaceId = $params["destPlaceId"];
		
		$recName = $params["recName"];
		$recAddress = $params["recAddress"];
		$recTel = $params["recTel"];
		$customerId = $params["customerId"];
		$sendAddress = $params["sendAddress"];
		$sendTel = $params["sendTel"];
		$cargo = $params["cargo"];
		$fragile = $params["fragile"];
		$freight = $params["freight"];
		$payment = $params["payment"];
		$claimValue = $params["claimValue"];
		$cargoMoney = $params["cargoMoney"];
		$memo = $params["memo"];
		
		$db = M();
		$db->startTrans();
		
		$sql = "select status, ref from t_express_bill where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			
			return $this->bad("要变更的运单不存在");
		}
		
		$oldRef = $data[0]["ref"];
		$statusBefore = $data[0]["status"];
		
		// 检查客户是否存在
		$sql = "select name from t_customer where id = '%s' ";
		$data = $db->query($sql, $customerId);
		if (! $data) {
			$db->rollback();
			return $this->bad("选择的托镖人不存在");
		}
		$sendName = $data[0]["name"];
		
		$sql = "update t_express_bill
				set status = %d, rec_name = '%s', rec_address = '%s', rec_tel = '%s', 
					send_name = '%s', send_address = '%s', send_tel = '%s', customer_id = '%s',
					cargo = '%s', is_fragile = %d, freight = %f, payment = %d, claim_value = %f,
					cargo_money = %f, memo = '%s', ref = '%s', start_place = '%s', dest_place = '%s',
					send_district_id = '%s', rec_district_id = '%s'
				where id = '%s' ";
		$rc = $db->execute($sql, $status, $recName, $recAddress, $recTel, $sendName, $sendAddress, 
				$sendTel, $customerId, $cargo, $fragile, $freight, $payment, $claimValue, 
				$cargoMoney, $memo, $ref, $startPlace, $destPlace, $startPlaceId, $destPlaceId, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 运单跟踪信息
		$us = new UserService();
		$userId = $us->getLoginUserId();
		
		$sql = "insert into t_express_tracing (ref, bill_id, status_before, status_after,
				changed_dt, op_user_id, memo)
				values ('%s', '%s', %d, %d, now(), '%s', '运单变更')";
		$rc = $db->execute($sql, $ref, $id, $statusBefore, $status, $userId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 同步一下运单号
		if ($ref != $oldRef) {
			$sql = "update t_express_tracing set ref = '%s' where bill_id = '%s' ";
			$rc = $db->execute($sql, $ref, $id);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		$bd = new BizlogDAO($db);
		$log = "运单变更，运单单号[$ref]";
		$bd->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok($id);
	}

	public function companyList() {
		$db = M();
		$sql = "select id, name
				from t_express_company
				order by name";
		$data = $db->query($sql);
		
		$result = array();
		foreach ( $data as $i => $v ) {
			$result[$i]["id"] = $v["id"];
			$result[$i]["name"] = $v["name"];
		}
		
		return $result;
	}

	public function editCompany($params) {
		$id = $params["id"];
		$name = $params["name"];
		
		$db = M();
		
		$db->startTrans();
		
		$us = new UserService();
		$dataOrg = $us->getLoginUserDataOrg();
		$companyId = $us->getCompanyId();
		
		$ps = new PinyinService();
		$py = $ps->toPY($name);
		
		$log = null;
		
		if ($id) {
			// 编辑
			$sql = "select count(*) as cnt from t_express_company 
					where name = '%s' and id <> '%s' ";
			$data = $db->query($sql, $name, $id);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("快递公司[$name]已经存在");
			}
			
			$sql = "update t_express_company
					set name = '%s', py = '%s'
					where id = '%s' ";
			$rc = $db->execute($sql, $name, $py, $id);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "编辑快递公司[$name]";
		} else {
			// 新建
			$sql = "select count(*) as cnt from t_express_company where name = '%s' ";
			$data = $db->query($sql, $name);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("快递公司[$name]已经存在");
			}
			
			$idGen = new IdGenService();
			$id = $idGen->newId($db);
			
			$sql = "insert into t_express_company (id, name, py, data_org, company_id)
					values ('%s', '%s', '%s', '%s', '%s')";
			$rc = $db->execute($sql, $id, $name, $py, $dataOrg, $companyId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "新建快递公司[$name]";
		}
		
		if ($log) {
			$bld = new BizlogDAO($db);
			$bld->insertBizlog($log, $this->LOG_CATEGORY);
		}
		
		$db->commit();
		
		return $this->ok($id);
	}

	public function deleteCompany($params) {
		$id = $params["id"];
		
		$db = M();
		$db->startTrans();
		$sql = "select name from t_express_company where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("要删除的快递公司不存在");
		}
		$name = $data[0]["name"];
		
		$sql = "select count(*) as cnt from t_so_bill where express_company_id = '%s' ";
		$data = $db->query($sql, $id);
		$cnt = $data[0]["cnt"];
		if ($cnt > 0) {
			$db->rollback();
			return $this->bad("快递公司[$name]已经在销售订单中使用了，不能删除");
		}
		
		$sql = "delete from t_express_company where id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$log = "删除快递公司[$name]";
		$bld = new BizlogDAO($db);
		$bld->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok();
	}

	private function initDefaultPrintItems() {
		$result = array();
		
		$result[] = array(
				"name" => "收件人-姓名",
				"caption" => "收件人-姓名"
		);
		
		$result[] = array(
				"name" => "收件人-淘宝昵称",
				"caption" => "收件人-淘宝昵称"
		);
		
		$result[] = array(
				"name" => "收件人-电话",
				"caption" => "收件人-电话"
		);
		
		$result[] = array(
				"name" => "收件人-省",
				"caption" => "收件人-省"
		);
		
		$result[] = array(
				"name" => "收件人-市",
				"caption" => "收件人-市"
		);
		
		$result[] = array(
				"name" => "收件人-区",
				"caption" => "收件人-区"
		);
		
		$result[] = array(
				"name" => "收件人-地址",
				"caption" => "收件人-地址"
		);
		
		$result[] = array(
				"name" => "商品概要",
				"caption" => "商品概要"
		);
		
		$result[] = array(
				"name" => "发件人-姓名",
				"caption" => "发件人-姓名"
		);
		
		$result[] = array(
				"name" => "发件人-电话",
				"caption" => "发件人-电话"
		);
		
		$result[] = array(
				"name" => "发件人-地址",
				"caption" => "发件人-地址"
		);
		
		return $result;
	}

	public function getExpressBillTemplateInfo($params) {
		$result = array(
				"hasData" => false,
				"defaultPageValue" => array(
						"pageTop" => 0,
						"pageLeft" => 0,
						"pageWidth" => 230,
						"pageHeight" => 127,
						"pageOrient" => 1
				),
				"defaultItems" => $this->initDefaultPrintItems()
		);
		
		$id = $params["id"];
		$db = M();
		$sql = "select id, page_top, page_left, page_width, page_height,
					page_orient
				from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			// 还没有设置过打印模板
			return $result;
		}
		
		$result["hasData"] = true;
		
		$v = $data[0];
		$pageId = $v["id"];
		$result["pageInfo"] = array(
				"pageTop" => $v["page_top"],
				"pageLeft" => $v["page_left"],
				"pageWidth" => $v["page_width"],
				"pageHeight" => $v["page_height"],
				"pageOrient" => $v["page_orient"]
		);
		
		$sql = "select name, item_top, item_left, item_width, item_height, caption,
					font_size
				from t_express_bill_printitem
				where page_id = '%s' ";
		$data = $db->query($sql, $pageId);
		$items = array();
		foreach ( $data as $v ) {
			$v = array(
					"name" => $v["name"],
					"itemTop" => $v["item_top"],
					"itemLeft" => $v["item_left"],
					"itemWidth" => $v["item_width"],
					"itemHeight" => $v["item_height"],
					"caption" => $v["caption"],
					"fontSize" => $v["font_size"]
			);
			
			$items[] = $v;
		}
		
		$result["items"] = $items;
		
		return $result;
	}

	public function editExpressBillTemplate($params) {
		$json = $params["jsonStr"];
		
		$bill = json_decode(html_entity_decode($json), true);
		if ($bill == null) {
			return $this->bad("传入的参数错误，不是正确的JSON格式");
		}
		
		$idGen = new IdGenService();
		
		$db = M();
		$db->startTrans();
		
		$expressCompanyId = $bill["companyId"];
		
		$pageLeft = $bill["pageLeft"];
		$pageTop = $bill["pageTop"];
		$pageWidth = $bill["pageWidth"];
		$pageHeight = $bill["pageHeight"];
		$pageOrient = $bill["pageOrient"];
		
		$items = $bill["items"];
		
		$sql = "select id
				from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $expressCompanyId);
		
		if (! $data) {
			// 首次设置模板
			
			$pageId = $idGen->newId($db);
			
			$sql = "insert into t_express_bill_printpage (id, express_company_id, name, 
						page_top, page_left, page_width, page_height, page_orient)
					values ('%s', '%s','默认模板', %f, %f, %f, %f , %d)";
			$rc = $db->execute($sql, $pageId, $expressCompanyId, $pageTop, $pageLeft, $pageWidth, 
					$pageHeight, $pageOrient);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$index = 0;
			foreach ( $items as $v ) {
				$selected = $v["selected"];
				if (! $selected) {
					continue;
				}
				
				$id = $idGen->newId($db);
				$name = $v["name"];
				$caption = $v["caption"];
				
				$top = $index * 30;
				$index += 1;
				
				$sql = "insert into t_express_bill_printitem (id, page_id, name, caption, 
							item_top, item_left, item_width, item_height, font_size)
						values ('%s', '%s', '%s', '%s', %f, 50, 100, 20, 9)";
				$rc = $db->execute($sql, $id, $pageId, $name, $caption, $top);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
		} else {
			$pageId = $data[0]["id"];
			
			// 编辑模板
			$sql = "update t_express_bill_printpage
					set page_left = %f, page_top = %f, page_width = %f, page_height = %f,
						page_orient = %d
					where id = '%s' ";
			$rc = $db->execute($sql, $pageLeft, $pageTop, $pageWidth, $pageHeight, $pageOrient, 
					$pageId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$index = 0;
			foreach ( $items as $v ) {
				$name = $v["name"];
				$caption = $v["caption"];
				
				$selected = $v["selected"];
				if (! $selected) {
					$sql = "delete from t_express_bill_printitem
							where page_id = '%s' and name = '%s' ";
					$rc = $db->execute($sql, $pageId, $name);
					if ($rc === false) {
						$db->rollback();
						return $this->sqlError(__LINE__);
					}
					
					continue;
				}
				
				$sql = "select id from t_express_bill_printitem
						where page_id = '%s' and name = '%s' ";
				$data = $db->query($sql, $pageId, $name);
				if ($data) {
					// 已经存在就不做处理
					
					continue;
				}
				
				$top = $index * 30;
				$index += 1;
				
				$id = $idGen->newId($db);
				
				$sql = "insert into t_express_bill_printitem (id, page_id, name, caption, 
							item_top, item_left, item_width, item_height, font_size)
						values ('%s', '%s', '%s', '%s', %f, 50, 100, 20, 9)";
				$rc = $db->execute($sql, $id, $pageId, $name, $caption, $top);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
		}
		
		$db->commit();
		
		return $this->ok();
	}

	public function getTemplateInfo($params) {
		$result = array(
				"hasData" => false
		);
		
		$id = $params["id"];
		$db = M();
		$sql = "select id, page_top, page_left, page_width, page_height,
					page_orient
				from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			// 还没有设置过打印模板
			return $result;
		}
		
		$result["hasData"] = true;
		
		$v = $data[0];
		$pageId = $v["id"];
		$result["pageInfo"] = array(
				"pageTop" => $v["page_top"],
				"pageLeft" => $v["page_left"],
				"pageWidth" => $v["page_width"],
				"pageHeight" => $v["page_height"],
				"pageOrient" => $v["page_orient"] == 1 ? "纵向打印" : "横向打印"
		);
		
		$sql = "select caption, item_left, item_top, item_width, item_height, font_size, is_bold
				from t_express_bill_printitem
				where page_id = '%s' ";
		$data = $db->query($sql, $pageId);
		$items = array();
		foreach ( $data as $v ) {
			$v = array(
					"caption" => $v["caption"],
					"left" => $v["item_left"],
					"top" => $v["item_top"],
					"width" => $v["item_width"],
					"height" => $v["item_height"],
					"fontSize" => $v["font_size"],
					"isBold" => $v["is_bold"] == 1 ? "是" : ""
			);
			
			$items[] = $v;
		}
		
		$result["items"] = $items;
		
		return $result;
	}

	public function getTemplateInfoForDesign($params) {
		$result = array(
				"hasPrintData" => false
		);
		
		$id = $params["id"];
		$db = M();
		$sql = "select id, page_top, page_left, page_width, page_height,
					page_orient
				from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			// 还没有设置过打印模板
			return $result;
		}
		$result["hasPrintData"] = true;
		
		$v = $data[0];
		$pageId = $v["id"];
		$result["pageId"] = $pageId;
		$result["pageInfo"] = array(
				"pageTop" => $v["page_top"],
				"pageLeft" => $v["page_left"],
				"pageWidth" => $v["page_width"],
				"pageHeight" => $v["page_height"],
				"pageOrient" => $v["page_orient"]
		);
		
		$sql = "select name, caption, item_left, item_top, item_width, item_height, font_size, is_bold
				from t_express_bill_printitem
				where page_id = '%s' ";
		$data = $db->query($sql, $pageId);
		$items = array();
		foreach ( $data as $v ) {
			$v = array(
					"name" => $v["name"],
					"caption" => $v["caption"],
					"left" => $v["item_left"],
					"top" => $v["item_top"],
					"width" => $v["item_width"],
					"height" => $v["item_height"],
					"fontSize" => $v["font_size"],
					"isBold" => $v["is_bold"]
			);
			
			$items[] = $v;
		}
		
		$result["items"] = $items;
		
		return $result;
	}

	public function designExpressBillTemplate($params) {
		$json = $params["jsonStr"];
		
		$bill = json_decode(html_entity_decode($json), true);
		if ($bill == null) {
			return $this->bad("传入的参数错误，不是正确的JSON格式");
		}
		
		$idGen = new IdGenService();
		
		$db = M();
		$db->startTrans();
		
		$expressCompanyId = $bill["companyId"];
		
		$pageLeft = $bill["pageLeft"];
		$pageTop = $bill["pageTop"];
		$pageWidth = $bill["pageWidth"];
		$pageHeight = $bill["pageHeight"];
		$pageOrient = $bill["pageOrient"];
		
		$items = $bill["items"];
		
		$sql = "select id
				from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $expressCompanyId);
		
		if (! $data) {
			// 首次设置模板
			
			$pageId = $idGen->newId($db);
			
			$sql = "insert into t_express_bill_printpage (id, express_company_id, name, 
						page_top, page_left, page_width, page_height, page_orient)
					values ('%s', '%s','默认模板', %f, %f, %f, %f , %d)";
			$rc = $db->execute($sql, $pageId, $expressCompanyId, $pageTop, $pageLeft, $pageWidth, 
					$pageHeight, $pageOrient);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			foreach ( $items as $v ) {
				$id = $idGen->newId($db);
				$name = $v["name"];
				$caption = $v["caption"];
				$left = $v["left"];
				$top = $v["top"];
				$width = $v["width"];
				$height = $v["height"];
				$fontSize = $v["fontSize"];
				$isBold = $v["isBold"];
				
				$sql = "insert into t_express_bill_printitem (id, page_id, name, caption, 
							item_top, item_left, item_width, item_height, font_size, is_bold)
						values ('%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d)";
				$rc = $db->execute($sql, $id, $pageId, $name, $caption, $top, $left, $width, 
						$height, $fontSize, $isBold);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
		} else {
			$pageId = $data[0]["id"];
			
			// 编辑模板
			$sql = "update t_express_bill_printpage
					set page_left = %f, page_top = %f, page_width = %f, page_height = %f,
						page_orient = %d
					where id = '%s' ";
			$rc = $db->execute($sql, $pageLeft, $pageTop, $pageWidth, $pageHeight, $pageOrient, 
					$pageId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$sql = "delete from t_express_bill_printitem where page_id = '%s' ";
			$rc = $db->execute($sql, $pageId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			foreach ( $items as $v ) {
				$id = $idGen->newId($db);
				$name = $v["name"];
				$caption = $v["caption"];
				$left = $v["left"];
				$top = $v["top"];
				$width = $v["width"];
				$height = $v["height"];
				$fontSize = $v["fontSize"];
				$isBold = $v["isBold"];
				
				$sql = "insert into t_express_bill_printitem (id, page_id, name, caption,
							item_top, item_left, item_width, item_height, font_size, is_bold)
						values ('%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d)";
				$rc = $db->execute($sql, $id, $pageId, $name, $caption, $top, $left, $width, 
						$height, $fontSize, $isBold);
				if ($rc === false) {
					$db->rollback();
					return $this->sqlError(__LINE__);
				}
			}
		}
		
		$db->commit();
		
		return $this->ok();
	}

	public function deleteDesignBill($params) {
		$id = $params["id"];
		
		$db = M();
		
		$db->startTrans();
		
		$sql = "select id from t_express_bill_printpage
				where express_company_id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("打印样式还没有建立，无需重置");
		}
		
		$pageId = $data[0]["id"];
		$sql = "delete from t_express_bill_printitem
				where page_id = '%s' ";
		$rc = $db->execute($sql, $pageId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$sql = "delete from t_express_bill_printpage
				where id = '%s' ";
		$rc = $db->execute($sql, $pageId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$db->commit();
		
		return $this->ok();
	}

	public function editSenderInfo($params) {
		$name = $params["name"];
		$tel = $params["tel"];
		$address = $params["address"];
		
		$db = M();
		$db->startTrans();
		
		$us = new UserService();
		$companyId = $us->getCompanyId();
		
		// 发件人姓名
		$id = "发件人姓名";
		$sql = "delete from t_config
				where company_id = '%s' and id = '%s' ";
		$rc = $db->execute($sql, $companyId, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		$showOrder = 10000;
		$sql = "insert into t_config(id, name, value, note, show_order, company_id)
				values ('%s','%s', '%s', '', %d, '%s') ";
		$rc = $db->execute($sql, $id, $id, $name, $showOrder, $companyId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 发件人电话
		$id = "发件人电话";
		$sql = "delete from t_config
				where company_id = '%s' and id = '%s' ";
		$rc = $db->execute($sql, $companyId, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		$showOrder = 10001;
		$sql = "insert into t_config(id, name, value, note, show_order, company_id)
				values ('%s','%s', '%s', '', %d, '%s') ";
		$rc = $db->execute($sql, $id, $id, $tel, $showOrder, $companyId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 发件人地址
		$id = "发件人地址";
		$sql = "delete from t_config
				where company_id = '%s' and id = '%s' ";
		$rc = $db->execute($sql, $companyId, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		$showOrder = 10002;
		$sql = "insert into t_config(id, name, value, note, show_order, company_id)
				values ('%s','%s', '%s', '', %d, '%s') ";
		$rc = $db->execute($sql, $id, $id, $address, $showOrder, $companyId);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$db->commit();
		
		return $this->ok();
	}

	public function getSenderInfo() {
		$result = array();
		
		$db = M();
		$us = new UserService();
		$companyId = $us->getCompanyId();
		
		$id = "发件人姓名";
		$sql = "select value
				from t_config
				where company_id = '%s' and id = '%s' ";
		$data = $db->query($sql, $companyId, $id);
		if ($data) {
			$result["name"] = $data[0]["value"];
		}
		
		$id = "发件人电话";
		$sql = "select value
				from t_config
				where company_id = '%s' and id = '%s' ";
		$data = $db->query($sql, $companyId, $id);
		if ($data) {
			$result["tel"] = $data[0]["value"];
		}
		
		$id = "发件人地址";
		$sql = "select value
				from t_config
				where company_id = '%s' and id = '%s' ";
		$data = $db->query($sql, $companyId, $id);
		if ($data) {
			$result["address"] = $data[0]["value"];
		}
		return $result;
	}
}